package com.atom.module.mvvm.livedata

import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

open class SingleLiveData<V> : AbstractLivaData<SingleLiveData.Type, V> {

    enum class Type {
        UI, NUI, ALL
    }

    private val mPending = AtomicBoolean(false)

    constructor(value: V) : super(Type.ALL, value)

    constructor() : super()

    @MainThread
    override fun observe(
        owner: LifecycleOwner,
        observer: Observer<in Pack<Type, V>>
    ) {
        super.observe(owner, { t ->
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(t)
            }
        })
    }

    public override fun postValue(value: Pack<Type, V>?) {
        super.postValue(value)
    }

    fun post(value: V?) {
        value?.also {
            postValue(Pack(Type.ALL, it))
        } ?: also {
            postValue(null)
        }
    }

    public override fun setValue(value: Pack<Type, V>?) {
        mPending.set(true)
        super.setValue(value)
    }

    fun set(value: V?) {
        value?.also {
            setValue(Pack(Type.ALL, it))
        } ?: also {
            setValue(null)
        }
    }
}